#include <crow.h>
#include <string>
#include <filesystem>
#include <fstream>
#include "controllers/default.hpp"
#include "utils/template_manager.hpp"
#include "utils/session_manager.hpp"

bool endsWith(const std::string& str, const std::string& suffix) {
    if (str.length() < suffix.length()) {
        return false;
    }
    return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
}

int getPortFromConfig() {
    std::ifstream configFile("conf/app.conf");
    std::string line;
    int port = 8080; // 默认端口
    
    if (configFile.is_open()) {
        while (std::getline(configFile, line)) {
            if (line.find("httpport") != std::string::npos) {
                size_t pos = line.find("=");
                if (pos != std::string::npos) {
                    port = std::stoi(line.substr(pos + 1));
                }
            }
        }
        configFile.close();
    }
    return port;
}

int main() {
    crow::SimpleApp app;
    
    // 设置模板目录（使用绝对路径）
    std::filesystem::path current_path = std::filesystem::current_path();
    std::filesystem::path template_dir = current_path.parent_path() / "views";
    TemplateManager::getInstance().setTemplateDir(template_dir.string());
    TemplateManager::getInstance().setLayout("layout.html");
    
    // 初始化会话管理器
    SessionManager::getInstance();
    
    // 创建控制器实例
    MainController controller;
    
    // 注册路由
    MainController::registerRoutes(app);
    
    // 设置错误处理
    CROW_ROUTE(app, "/error")
    ([]() {
        return crow::response(500, "Internal Server Error");
    });
    
    // 设置CORS
    CROW_ROUTE(app, "/<path>")
    .methods("OPTIONS"_method)
    ([](const std::string& path) {
        auto res = crow::response(200);
        res.set_header("Access-Control-Allow-Origin", "*");
        res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.set_header("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
        return res;
    });
    
    // 启动服务器
    app.port(getPortFromConfig()).multithreaded().run();
    return 0;
} 